/*
 *  Copyright 2004 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.action.news;

import com.blandware.atleap.common.NewsModuleConstants;
import com.blandware.atleap.model.core.ContentLocale;
import com.blandware.atleap.model.news.NewsItem;
import com.blandware.atleap.service.news.NewsManager;
import com.blandware.atleap.webapp.action.core.BaseAction;
import com.blandware.atleap.webapp.form.news.NewsItemForm;
import com.blandware.atleap.webapp.util.core.LocaleUtil;
import com.blandware.atleap.webapp.util.core.WebappConstants;
import com.blandware.atleap.webapp.util.core.WebappUtil;
import com.blandware.atleap.webapp.util.news.NewsModuleWebConstants;
import org.apache.commons.validator.GenericValidator;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * <p>Prepares form bean to update news item's data
 * </p>
 * <p><a href="CallUpdateNewsItemAction.java.html"><i>View Source</i></a></p>
 * <p/>
 *
 * @author Sergey Zubtsovskiy <a href="mailto:sergey.zubtsovskiy@blandware.com">&lt;sergey.zubtsovskiy@blandware.com&gt;</a>
 * @version $Revision: 1.23 $ $Date: 2008/04/29 17:51:52 $
 * @struts.action path="/news/callUpdateItem"
 * name="newsItemForm"
 * scope="request"
 * validate="false"
 * roles="news-item-update, news-item-view"
 * @struts.action-forward name="updateNewsItem"
 * path=".news.updateItem"
 * @struts.action-forward name="listNewsItems"
 * path="/news/listItems.do"
 * redirect="true"
 */
public final class CallUpdateNewsItemAction extends BaseAction {
	/**
	 * @param mapping  The ActionMapping used to select this instance
	 * @param form     The optional ActionForm bean for this request (if any)
	 * @param request  The HTTP request we are proceeding
	 * @param response The HTTP response we are creating
	 * @return an ActionForward instance describing where and how
	 *         control should be forwarded, or null if response
	 *         has already been completed
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
	                             HttpServletRequest request, HttpServletResponse response) throws Exception {

		request.getSession().removeAttribute(NewsModuleWebConstants.NEWS_ITEM_SUBMITTED_ACTION_KEY);

		if ( isCancelled(request) ) {
            request.getSession().removeAttribute(NewsModuleWebConstants.NEWS_ITEM_MERGED_ANNOTATION_KEY);
            request.getSession().removeAttribute(NewsModuleWebConstants.NEWS_ITEM_MERGED_BODY_KEY);
            return mapping.findForward("listNewsItems");
		}

		if ( !request.isUserInRole("news-item-update") ) {
			response.sendError(HttpServletResponse.SC_FORBIDDEN);
			return null;
		}

		NewsItemForm newsItemForm = (NewsItemForm) form;
		Long newsItemId;
		if ( newsItemForm.getId() != null ) {
			newsItemId = Long.valueOf(newsItemForm.getId());
		} else if ( request.getAttribute(NewsModuleWebConstants.NEWS_ITEM_ID_KEY) != null ) {
			newsItemId = (Long) request.getAttribute(NewsModuleWebConstants.NEWS_ITEM_ID_KEY);
		} else if ( request.getSession().getAttribute(NewsModuleWebConstants.NEWS_ITEM_ID_KEY) != null ) {
			newsItemId = (Long) request.getSession().getAttribute(NewsModuleWebConstants.NEWS_ITEM_ID_KEY);
		} else {
			if ( log.isWarnEnabled() ) {
				log.warn("Missing news item ID. Returning to list...");
			}
			return mapping.findForward("listNewsItems");
		}

		String redirectUrl = request.getParameter("redirectUrl");
		if ( GenericValidator.isBlankOrNull(redirectUrl) ) {
			redirectUrl = (String) request.getAttribute(WebappConstants.REDIRECT_URL_KEY);
		}
		if ( !GenericValidator.isBlankOrNull(redirectUrl) ) {
			request.getSession().setAttribute(WebappConstants.REDIRECT_URL_KEY, redirectUrl);
		} else {
			request.getSession().removeAttribute(WebappConstants.REDIRECT_URL_KEY);
		}

		String localesMode = newsItemForm.getLocalesMode();
		if ( !"current".equalsIgnoreCase(localesMode) && !"all".equalsIgnoreCase(localesMode) ) {
			localesMode = "selected";
		}
		newsItemForm.setLocalesMode(localesMode);

		NewsManager newsManager = (NewsManager) getBean(NewsModuleConstants.NEWS_MANAGER_BEAN);
		NewsItem newsItem = newsManager.retrieveNewsItem(newsItemId);
		if ( newsItem == null ) {
			// newsItem not found. it might be deleted by someone else
			ActionMessages errors = new ActionMessages();
			errors.add("newsItemNotFound", new ActionMessage("news.errors.notFound"));
			saveErrors(request, errors);
			return mapping.findForward("listNewsItems");
		}
		WebappUtil.copyProperties(newsItemForm, newsItem, request);
		newsItemForm.setTitleMap(newsItem.getTitle());
		newsItemForm.setAnnotationMap(newsItem.getAnnotation());
		newsItemForm.setBodyMap(newsItem.getBody());

		List contentLocales = LocaleUtil.getInstance(servlet.getServletContext()).getEnabledLocales();

        if ("selected".equalsIgnoreCase(localesMode)) {
            // mark all locales as checked
            Map annotationCheckedBoxes = newsItemForm.getAnnotationCheckedBoxes();
            for (Iterator i = contentLocales.iterator(); i.hasNext();) {
                ContentLocale contentLocale = (ContentLocale) i.next();
                annotationCheckedBoxes.put(contentLocale.getIdentifier(), Boolean.TRUE);
            }

            // check 'check all' ckeckbox
            if ("selected".equalsIgnoreCase(localesMode)) {
                request.setAttribute(WebappConstants.SELECT_ALL_LOCALES_CHECKBOX_IS_CHECKED, Boolean.TRUE);
            }            
        }

		request.getSession().setAttribute(WebappConstants.CONTENT_LOCALES_COLLECTION_KEY, contentLocales);

		// save transaction token in request
		saveToken(request);
		return mapping.findForward("updateNewsItem");
	}

}